// pages/user/user/applyUnit/applyUnit.js
const app = getApp();
// 引入SDK核心类
var QQMapWX = require('../../../../utils/qqmap-wx-jssdk.min.js');
var key = app.globalData.qqmapsdk;
var qqmapsdk = new QQMapWX({
  key: key
});
import Api from '../../../../utils/http';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    addPicList: [], //证明图片集
    adminPicList: [], //管理员证件
    imgarr: [], //证明图片集id
    imgarrs: [], //管理员证件id
    address: '',
    isDel: false,
    chooseViewShow: true,
    currPickerItem: '请选择单位类型', //当前选中
    currPickerIndex: '', //选中id
    typeId: -1,
    pickerItemArr: [],//单位类型数组
  },
  //选择地址
  chooseLocation: function () {
    var that = this
    wx.chooseLocation({
      // latitude: wx.getStorageSync('latLng').lat,
      // longitude: wx.getStorageSync('latLng').lng,
      success: function (res) {
        console.log(res)
        that.setData({
          lng: res.longitude,
          lat: res.latitude,
        })
        that.FormSubmit();
      }
    })
  },
  //选择类型
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var pickerItemArr = this.data.pickerItemArr;
    if(e.detail.value!=isNaN){
      
    };
    this.setData({
      index: e.detail.value,
      currPickerIndex: e.detail.value,
      currPickerItem: pickerItemArr[e.detail.value].title,
      typeId: pickerItemArr[e.detail.value].id
    })
  },
  /** 提交证明、管理上传图片 */
  uploadPic: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    let {
      isDel,
      addPicList,
      adminPicList,
      imgarr,
      imgarrs,
    } = that.data
    if (addPicList.length >= 0) {
      that.setData({
        isDel: true
      })
    }
    // that.chooseViewShow()
    // if (that.data.addPicList.length < 3) {

    // }

    wx.chooseImage({
      count: 5, //最多选择几张图片
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        wx.showLoading({
          title: '正在上传中',
          mask: true,
        })
        let webSiteUrl = app.globalData.webSiteUrl
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        // var imgArrNow = that.data.addPicList;
        // imgArrNow = imgArrNow.concat(res.tempFilePaths);
        // that.setData({
        //   addPicList: imgArrNow
        // })
        console.log(tempFilePaths[0])
        wx.uploadFile({
          url: webSiteUrl + '/app/Upload/upload', //接口地址
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {},
          success(res) {
            wx.hideLoading();
            var data = res.data
            data = JSON.parse(data);
            console.log(data)
            if (type == 1) {
              that.setData({
                addPicList: addPicList.concat(data.data),
                imgarr: imgarr.concat(data.data.id)
              })
            } else {
              that.setData({
                adminPicList: adminPicList.concat(data.data),
                imgarrs: imgarrs.concat(data.data.id)
              })
            }
          }
        })

        //that.chooseViewShow();
      }
    })
  },


  /** 删除图片 */
  deleteImvAddPicList: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    var addPicList = that.data.addPicList;
    var imgarr = that.data.imgarr;
    var adminPicList = that.data.adminPicList;
    var imgarrs = that.data.imgarrs;
    var itemIndex = e.currentTarget.dataset.index;
    if (type == 1) {
      //删除证明图片
      addPicList.splice(itemIndex, 1);
      imgarr.splice(itemIndex, 1);
      that.setData({
        addPicList: addPicList,
        imgarr: imgarr
      })
      console.log(addPicList)
    } else {
      //删除管理员证件图片
      adminPicList.splice(itemIndex, 1);
      imgarrs.splice(itemIndex, 1);
      that.setData({
        adminPicList: adminPicList,
        imgarrs: imgarrs
      })
      console.log(adminPicList)
    }

    //判断是否隐藏选择图片
    that.chooseViewShow();
  },
  /** 是否隐藏图片选择*/
  chooseViewShow: function () {
    let {
      addPicList,
      adminPicList
    } = this.data
    if (addPicList.length >= 3 || adminPicList.length >= 3) {
      this.setData({
        chooseViewShow: false
      })
    } else {
      this.setData({
        chooseViewShow: true
      })
    }
  },
  /** 查看大图 */
  // showImage: function (e) {
  //   var addPicList = this.data.addPicList;
  //   var itemIndex = e.currentTarget.dataset.id;
  //   console.log("itemIndex:" + JSON.stringify(e))
  //   wx.previewImage({
  //     current: addPicList[itemIndex], // 当前显示图片的http链接
  //     urls: addPicList // 需要预览的图片http链接列表
  //   })
  // },
  //请求提交单位申请接口
  formSubmit: function (e) {
    console.log('ss', e, this.data)
    var that = this;
    if (e.detail.value.unitname == " ") {
      wx.showModal({
        title: '提示',
        content: "请输入单位名称",
        showCancel: false,
        confirmColor: "#db3c40"
      })
    } else if (that.data.typeId == -1) {
      wx.showModal({
        title: "提示",
        content: "请输入单位类型",
        showCancel: false,
        confirmColor: "#db3c40"
      })
    } else if (e.detail.value.unitnumber.length == 0) {
      wx.showModal({
        title: "提示",
        content: "请输入单位人数",
        showCancel: false,
        confirmColor: "#db3c40"
      })
    }else if (e.detail.value.site == '') {
      wx.showModal({
        title: "提示",
        content: "请输入单位地址",
        showCancel: false,
        confirmColor: "#db3c40"
      })
    } else if (e.detail.value.adminname == '') {
      wx.showModal({
        title: "提示",
        content: "请输入管理名称",
        showCancel: false,
        confirmColor: "#db3c40"
      })
    } else if (that.data.adminphone == '' || !/^1[3456789]\d{9}$/.test(e.detail.value.adminphone)) {
      wx.showModal({
        title: "提示",
        content: "请输入管理电话",
        showCancel: false,
        confirmColor: "#db3c40"
      })
    } else if (that.data.adminPicList.length == 0 || that.data.addPicList.length == 0) {
      wx.showModal({
        title: '提示',
        content: "提交图片不能为空",
        showCancel: false,
        confirmColor: "#db3c40"
      })
    } else {
      that.getApplyManage(e);

    }
  },
  // submitForm: function () {
  // },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      options: options
    });
    that.getCategory();
  },
  //触发表单提交事件，调用接口
  FormSubmit() {
    var _this = this;
    //调用地址解析接口
    qqmapsdk.reverseGeocoder({
      //获取表单传入地址
      location: {
        latitude: _this.data.lat,
        longitude: _this.data.lng
      },
      //address:'', //地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
      success: function (res) { //成功后的回调
        console.log(res);
        var result = res.result;
        _this.setData({
          address: result.address
        })
        wx.setStorageSync('latLng', res.location)
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        // console.log(res);
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  //单位类型
  getCategory:function(){
    var that=this;
    var param={
      type: 1
    }
    Api.ajax('/app/Zarticle/category',param).then(res=>{
      console.log(res)
      if (res.code==200) {
        that.setData({
          pickerItemArr:res.data
        })
      }
    })
  },
  //管理员申请
  getApplyManage: function (e) {
    var that = this;
    console.log(that.data)
    var support = that.data.imgarr;
    var manage_img = that.data.imgarrs;
    var uid = wx.getStorageSync('userid').id;
    var param = {
      uid: uid,
      title: e.detail.value.unitname,
      user_num: e.detail.value.unitnumber,
      support: support.toString(),
      adress: e.detail.value.site,
      name: e.detail.value.adminname,
      mobile: e.detail.value.adminphone,
      type:that.data.typeId,
      manage_img: manage_img.toString(),
    };
    console.log(param)
    Api.ajax("/app/Zmanage/applyManage", param).then(res => {
      console.log(res)
      if (res.code == 200) {

        wx.showToast({
          title: res.msg, //这里成功
          icon: 'success',
          duration: 1000
        })
        wx.redirectTo({
          url: '/pages/user/user/applyResult/applyResult',
        })
      } else if (res.code == 202) {
        wx.showModal({
          title: '提示',
          content: '请前往认证，点击确定',
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/user/user/mobileAuth/mobileAuth',
              })
            } else if (res.cancel) {
              wx.showToast({
                title: '请输入正确信息',
                icon: 'none',
                duration: 1000
              })
            }
          }
        })
      } else {
        wx.showToast({
          title: '请填写完整信息', //这里失败
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})